﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace SAF.Controls.Test
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SplashScreen.Show();
            SplashScreen.Status = "正在加载系统...";
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            Application.Run(new Form1());
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex)
        {
            string message = string.Format("{0}\r\n操作发生错误，您需要退出系统么？", ex.Exception.Message);
            MessageBox.Show(message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            Environment.Exit(0);

        }

        public static bool SendToPreviousInstance()
        {
            bool success = false;
            NativeMethods.EnumWindows(
                (hWnd, lParam) =>
                {
                    string windowTitle = NativeMethods.GetWindowText(hWnd, 100);
                    if (windowTitle.StartsWith("SAF", StringComparison.Ordinal))
                    {

                        NativeMethods.SetForegroundWindow(hWnd);
                        success = true;
                        return false; // stop enumeration

                    }
                    return true; // continue enumeration
                }, IntPtr.Zero);
            return success;
        }

        //private unsafe static IntPtr Send(IntPtr hWnd, string message)
        //{
        //    const uint SMTO_NORMAL = 0;

        //    CopyDataStruct lParam;
        //    lParam.Padding = IntPtr.Zero;
        //    lParam.Size = message.Length * 2;
        //    fixed (char* buffer = message)
        //    {
        //        lParam.Buffer = (IntPtr)buffer;
        //        IntPtr result;
        //        // SendMessage with 3s timeout (e.g. when the target process is stopped in the debugger)
        //        if (NativeMethods.SendMessageTimeout(
        //            hWnd, NativeMethods.WM_COPYDATA, IntPtr.Zero, ref lParam,
        //            SMTO_NORMAL, 3000, out result) != IntPtr.Zero)
        //        {
        //            return result;
        //        }
        //        else
        //        {
        //            return IntPtr.Zero;
        //        }
        //    }
        //}
    }


}
